package com.qingchi.server.controller;

import com.qingchi.base.modelVO.user.UserDetailBO;
import com.socialuni.social.entity.SocialUserDetailEntity;
import com.socialuni.social.model.DO.user.SocialUserDO;
import com.socialuni.social.model.common.ResultRO;
import com.socialuni.social.constant.ErrorMsg;
import com.qingchi.base.platform.tencent.TencentCloud;
import com.qingchi.base.platform.weixin.HttpResult;
import com.qingchi.base.platform.weixin.WxUtil;
import com.qingchi.base.repository.user.UserRepository;
import com.socialuni.social.model.DO.user.SocialUserDetailDO;
import com.qingchi.base.repository.user.UserDetailRepository;
import com.qingchi.base.repository.user.UserImgRepository;
import com.socialuni.social.utils.AgeUtils;
import com.socialuni.social.utils.GenderUtil;
import com.socialuni.social.model.RO.user.UserDetailVO;
import com.qingchi.base.modelVO.user.UserEditVO;
import com.qingchi.base.service.IllegalWordService;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.Optional;

/**
 * 查询用户详情
 *
 * @author qinkaiyuan
 * @since 1.0.0
 */
@RestController
@RequestMapping("user")
public class UserUpdateController {
    @Resource
    private UserRepository userRepository;
    @Resource
    private UserDetailRepository userDetailRepository;
    @Resource
    private EntityManager entityManager;
    @Resource
    private UserImgRepository userImgRepository;
    @Resource
    private IllegalWordService illegalWordService;
    @Resource
    private SocialUserDetailEntity socialUserDetailEntity;

    @PostMapping("updateAvatar")
    public ResultRO<?> updateAvatar(@Valid @NotNull String avatar, SocialUserDO user) {
        //被举报状态的用户不能修改
        user.setAvatar("https://" + avatar);
        user.setUpdateTime(new Date());
        userRepository.save(user);
        return new ResultRO<>();
    }

    @PostMapping("edit")
    public ResultRO<UserDetailVO> editUser(SocialUserDO user, @RequestBody @Valid UserEditVO userEditVO) {

        //昵称
        String nickname = userEditVO.getNickname();
        if (StringUtils.isEmpty(nickname)) {
            return new ResultRO<>("昵称不能为空");
        }
        if (nickname.length() > 6) {
            return new ResultRO<>("昵称长度不能大于6");
        } else {
            ResultRO resultRO = illegalWordService.checkHasIllegals(nickname);
            //校验内容是否违规
            if (resultRO.hasError()) {
                return new ResultRO<>(resultRO);
            }
            if (TencentCloud.textIsViolation(nickname)) {
                return new ResultRO<>("昵称包含违规内容，禁止修改，请修改后重试");
            }
            HttpResult wxResult = WxUtil.checkContentWxSec(nickname);
            if (wxResult.hasError()) {
                return new ResultRO<>("昵称包含违规内容，禁止修改，请修改后重试");
            }
            user.setNickname(StringUtils.substring(nickname, 0, 6));
        }

        String editGender = GenderUtil.getUserEditGenderByOldGender(userEditVO.getGender());
        ResultRO<String> checkGender = GenderUtil.checkUserEditGenderType(editGender);

        if (checkGender.hasError()) {
            return new ResultRO<>(checkGender);
        }

        if (!user.getGender().equals(editGender)) {
            SocialUserDetailDO userDetailDO = userDetailRepository.findFirstOneByUserId(user.getUserId()).get();

            //如果性别修改过，则不可再修改
            if (userDetailDO.getGenderModified()) {
                return new ResultRO<>("用户已修改过性别，不可再次修改，" + ErrorMsg.CONTACT_SERVICE);
            }
            userDetailDO.setGenderModified(true);
            userDetailDO.setUpdateTime(new Date());
            userDetailRepository.save(userDetailDO);
        }

        user.setGender(editGender);

        //生日，年龄
        String birthday = userEditVO.getBirthday();
        if (StringUtils.isNotEmpty(birthday)) {
            user.setBirthday(birthday);
            user.setAge(AgeUtils.getAgeByBirth(birthday));
        }

        String location = userEditVO.getLocation();
        if (StringUtils.isEmpty(location)) {
            userEditVO.setLocation(userEditVO.getCity());
        }

        //保存地区名
        if (StringUtils.isNotEmpty(userEditVO.getLocation())) {
            if (userEditVO.getLocation().length() > 10) {
                return new ResultRO<>("市县区名称长度不能大于10");
            } else {
                String userLocation = userEditVO.getLocation();
                ResultRO resultRO = illegalWordService.checkHasIllegals(userLocation);
                //校验内容是否违规
                if (resultRO.hasError()) {
                    return new ResultRO<>(resultRO);
                }
                if (TencentCloud.textIsViolation(userLocation)) {
                    return new ResultRO<>("地区名称违规");
                }
                HttpResult wxResult = WxUtil.checkContentWxSec(userLocation);
                if (wxResult.hasError()) {
                    return new ResultRO<>("地区名称违规");
                }
//                user.setCity(userEditVO.getLocation());
            }
        }
        //保存用户详情相关，联系方式
        Optional<SocialUserDetailDO> optionalUserDetailDO = userDetailRepository.findFirstOneByUserId(user.getId());
        SocialUserDetailDO userDetailDO;
        userDetailDO = optionalUserDetailDO.orElseGet(() -> socialUserDetailEntity.create(user));
        String contactAccount = userEditVO.getContactAccount();
        String wxAccount = userEditVO.getWxAccount();
        String qqAccount = userEditVO.getQqAccount();
        String wbAccount = userEditVO.getWbAccount();
        //代表老版本
        if (contactAccount == null) {
            if (wxAccount != null) {
                if (StringUtils.isNotEmpty(wxAccount)) {
                    if (wxAccount.length() > 23) {
                        return new ResultRO<>("微信账户名不得超过23个字符，例如：491369310");
                    } else if (wxAccount.length() < 6) {
                        return new ResultRO<>("微信账户名必须大于5个字符，例如：491369310");
                    } else {
                        ResultRO resultRO = illegalWordService.checkHasIllegals(wxAccount);
                        //校验内容是否违规
                        if (resultRO.hasError()) {
                            return new ResultRO<>(resultRO);
                        }
                        if (TencentCloud.textIsViolation(wxAccount)) {
                            return new ResultRO<>("微信账户违规");
                        }
                        HttpResult wxResult = WxUtil.checkContentWxSec(wxAccount);
                        if (wxResult.hasError()) {
                            return new ResultRO<>("微信账户违规");
                        }
                    }
                }
                userDetailDO.setWxAccount(wxAccount);
            }
            if (qqAccount != null) {
                if (StringUtils.isNotEmpty(qqAccount)) {
                    if (qqAccount.length() > 15) {
                        return new ResultRO<>("qq号不得超过15个字符，例如：491369310");
                    } else if (qqAccount.length() < 5) {
                        return new ResultRO<>("qq号必须大于4个字符，例如：491369310");
                    } else {
                        ResultRO resultRO = illegalWordService.checkHasIllegals(qqAccount);
                        //校验内容是否违规
                        if (resultRO.hasError()) {
                            return new ResultRO<>(resultRO);
                        }
                        if (TencentCloud.textIsViolation(qqAccount)) {
                            return new ResultRO<>("qq号违规");
                        }
                        HttpResult wxResult = WxUtil.checkContentWxSec(qqAccount);
                        if (wxResult.hasError()) {
                            return new ResultRO<>("qq号违规");
                        }
                    }
                    userDetailDO.setQqAccount(qqAccount);
                }
            }
            if (wbAccount != null) {
                if (StringUtils.isNotEmpty(wbAccount)) {
                    if (wbAccount.length() > 20) {
                        return new ResultRO<>("微博名称不得超过20个字符，例如：清池");
                    } else if (wbAccount.length() < 2) {
                        return new ResultRO<>("微博名称必须大于1个字符，例如：清池");
                    } else {
                        ResultRO resultRO = illegalWordService.checkHasIllegals(wbAccount);
                        //校验内容是否违规
                        if (resultRO.hasError()) {
                            return new ResultRO<>(resultRO);
                        }
                        if (TencentCloud.textIsViolation(wbAccount)) {
                            return new ResultRO<>("微博名称违规");
                        }
                        HttpResult wxResult = WxUtil.checkContentWxSec(wbAccount);
                        if (wxResult.hasError()) {
                            return new ResultRO<>("微博名称违规");
                        }
                    }
                }
                userDetailDO.setWbAccount(wbAccount);
            }
            //老版本将其他的联系方式放置到联系方式上
            //如果微信不为空，且长度大于5
            if (StringUtils.isNotEmpty(wxAccount)) {
                contactAccount = "wx:" + wxAccount;
            } else if (StringUtils.isNotEmpty(qqAccount)) {
                contactAccount = "qq:" + qqAccount;
            } else if (StringUtils.isNotEmpty(wbAccount)) {
                contactAccount = "wb:" + wbAccount;
            } else {
                contactAccount = "";
            }
        } else {
            //新版本
            if (StringUtils.isNotEmpty(contactAccount)) {
                if (contactAccount.length() > 30) {
                    return new ResultRO<>("联系方式不能超过30个字符，例如：vx:491369310");
                } else if (contactAccount.length() < 5) {
                    return new ResultRO<>("联系方式必须大于4个字符，例如：vx:491369310");
                } else {
                    ResultRO resultRO = illegalWordService.checkHasIllegals(contactAccount);
                    //校验内容是否违规
                    if (resultRO.hasError()) {
                        return new ResultRO<>(resultRO);
                    }
                    if (TencentCloud.textIsViolation(contactAccount)) {
                        return new ResultRO<>("联系方式违规");
                    }
                    HttpResult wxResult = WxUtil.checkContentWxSec(contactAccount);
                    if (wxResult.hasError()) {
                        return new ResultRO<>("联系方式违规");
                    }
                }
            }
        }
        userDetailDO.setContactAccount(contactAccount);
        userDetailRepository.save(userDetailDO);
        user.setUpdateTime(new Date());
        return new ResultRO<>(new UserDetailBO(userRepository.save(user), true).toVO());
    }
}